import axios from '../plugins/axios.js';
import { computed } from 'vue';
import { get } from 'lodash-es';
import { defineStore } from 'pinia';
import { handleCommonRes } from '../utils/resolver.js';
import { turnArr2Obj } from '../utils/index.js';
import { useAutoAction, useAutoGetter } from './autoActionGetter.js';
import { getStoreId } from './utils.js';

function getDynamicData(name, storeKey, actionKey) {
  const dicDataStore = useDicDataStore();
  if (!dicDataStore[storeKey][name]) {
    dicDataStore[storeKey][name] = {};
    dicDataStore[actionKey](name);
  }
  return dicDataStore[storeKey][name];
}

const id = getStoreId('DicDataStore');

export const useDicDataStore = defineStore(id, {
  state: () => ({
    enumDataStore: {},
    dicDataStore: {},
    gbDataStore: {},
  }),
  getters: {
    getEnumData: useAutoGetter({
      getter: (state) => (name) => {
        const data = state.enumDataStore[name] || {};
        return data && data.length
          ? data.reduce((res, item) => {
              return Object.assign({}, res, { [item.value]: item.name });
            }, {})
          : {};
      },
      action: function (params) {
        this.getEnumDataAsync(params);
      },
    }),
    getEnumText: useAutoGetter({
      getter: (state) => (name, value) => get(state.enumDataStore, `${name}.${value}`) || '',
      action: function (params) {
        this.getEnumDataAsync(params);
      },
    }),
    getEnumDataList: useAutoGetter({
      getter: (state) => (name) => {
        const data = state.enumDataStore[name] || {};
        return data && data.length
          ? data.map((key) => {
              return { label: key.name, value: key.value };
            })
          : [];
      },
      action: function (params) {
        this.getEnumDataAsync(params);
      },
    }),
    getGbData: useAutoGetter({
      getter: (state) => (type) => state.gbDataStore[type] || {},
      action: function (params) {
        this.getGbDataAsync(params);
      },
    }),
    getGbText: useAutoGetter({
      getter: (state) => (type, value) => get(state.gbDataStore, `${type}.${value}`) || '',
      action: function (params) {
        this.getGbDataAsync(params);
      },
    }),
    getGbDataList: useAutoGetter({
      getter: (state) => (type) => {
        const data = state.gbDataStore[type] || {};
        return Object.keys(data).map((key) => {
          return { label: data[key], value: key };
        });
      },
      action: function (params) {
        this.getGbDataAsync(params);
      },
    }),
    getDicData: useAutoGetter({
      getter: (state) => (name) => state.dicDataStore[name] || {},
      action: function (params) {
        this.getDicDataAsync(params);
      },
    }),
    getDicText: useAutoGetter({
      getter: (state) => (name, value) => get(state.dicDataStore, `${name}.${value}`) || '',
      action: function (params) {
        this.getDicDataAsync(params);
      },
    }),
    getDicDataList: useAutoGetter({
      getter:
        (state) =>
        (name, valueKey = true) => {
          const data = state.dicDataStore[name] || {};
          return Object.keys(data).map((key) => {
            return { label: data[key], value: valueKey ? key : data[key] };
          });
        },
      action: function (params) {
        this.getDicDataAsync(params);
      },
    }),
  },
  actions: {
    /*
     * 枚举的类名,可接受的值如下,具体使用哪个需要结合接口说明
     * name: com.xwzn.constant.ManufacturersEnum,ManufacturersEnum,Manufacturers,manufacturers
     * */
    getEnumDataAsync: useAutoAction({
      action: async function (name) {
        name = name || 'com.xwzn.constant';
        const api = (name) => axios.get(`/xw-microservice/xw-system/v3/open/enum/${name}`);
        return (this.enumDataStore[name] = await handleCommonRes(api, name));
      },
    }),
    getDicDataAsync: useAutoAction({
      action: async function (name) {
        if (!name) return;
        const api = (name) => axios.get(`/xw-microservice/xw-system/v3/dic/getDicListByName`, { params: { name } });
        const data = await handleCommonRes(api, name);
        return (this.dicDataStore[name] = turnArr2Obj(data, {
          keyField: 'flag',
          valueField: 'dic_value',
        }));
      },
    }),
    getGbDataAsync: useAutoAction({
      action: async function (type) {
        if (!type) return;
        const api = (type) => axios.get(`/xw-microservice/xw-system/v3/open/gb/${type}`);
        const data = await handleCommonRes(api, type);
        let options = { keyField: 'code', valueField: 'value' };
        if (type == 'nation') {
          options = { keyField: 'value', valueField: 'value' };
        }
        return (this.gbDataStore[type] = turnArr2Obj(data, options));
      },
    }),
  },
});

export function getDicStore(name) {
  return getDynamicData(name, 'dicDataStore', 'getDicDataAsync');
}
export function getEnumStore(name) {
  return getDynamicData(name, 'enumDataStore', 'getEnumDataAsync');
}
export function getGbStore(name) {
  return getDynamicData(name, 'gbDataStore', 'getGbDataAsync');
}
export function getDynamicDicText(name, value) {
  return computed(() => {
    return getDicStore(name)[value];
  });
}
export function getDynamicEnumText(name, value) {
  return computed(() => {
    return getEnumStore(name)[value];
  });
}
export function getDynamicGbText(name, value) {
  return computed(() => {
    return getGbStore(name)[value];
  });
}
